<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" @change="changeFn" :checked="isAllChecked" />
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <GouWuChe
          v-for="(arr, index) in goodList"
          :key="index"
          :obj="arr"
          :index="index"
          @addFn="babaAddFn"
          @jianFn="babaJianFn"
          @delFn="babaDelFn"
        />
      </tbody>
      <tfoot>
        <tr>
          <td>合计:{{ sum }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import GouWuChe from "./components/GouWuChe.vue";
export default {
  computed: {
    sum() {
      return this.goodList.reduce((item, val) => {
        if (val.checked == true) {
          item += val.price * val.num;
        }
        return item;
      }, 0);
    },
    isAllChecked() {
      return this.goodList.every((item) => item.checked == true);
    },
  },
  methods: {
    babaAddFn(i) {
      this.goodList[i].num++;
    },
    babaJianFn(ind) {
      this.goodList[ind].num--;
    },
    babaDelFn(index) {
      this.goodList.splice(index, 1);
    },
    changeFn(e) {
      this.goodList.forEach((item) => (item.checked = e.target.checked));
    },
  },
  components: {
    GouWuChe,
  },
  data() {
    return {
      sums: "",
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
};
</script>

<style>
</style>